package com.boot.file.controller;

import com.boot.file.service.FileService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author 公众号:知了一笑
 * @since 2023-07-15 14:03
 */
@RestController
public class FileWeb {

    private static final Logger logger = LoggerFactory.getLogger(FileWeb.class);

    @Resource
    private FileService fileService ;

    @PostMapping("/file/upload")
    public String upload (HttpServletRequest request,
                          @RequestParam("file") MultipartFile[] fileList) throws Exception {
        String uploadUser = request.getParameter("uploadUser");
        if (uploadUser.isEmpty()){
            return "upload-user is empty";
        }
        logger.info("upload-user:{}",uploadUser);
        for (MultipartFile multipartFile : fileList) {
            fileService.dealFile(multipartFile);
        }
        return "success" ;
    }

    /**
     * 请求地址：
     * /file/download?fileName=image-test.png
     */
    @GetMapping("/file/download")
    public void upload (@RequestParam("fileName") String fileName,
                          HttpServletResponse response) throws Exception {
        if (!fileName.isBlank()){
            String filePath = ResourceUtils.getURL("m1-04-boot-file/src/main/resources/file").getPath();
            File file = new File(filePath,fileName) ;
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
            response.setContentType("application/octet-stream");
            Files.copy(Paths.get(file.getPath()), response.getOutputStream());
        }
    }
}
